#!/usr/bin/env python
# -*- coding:utf-8 -*- #

import os
from popcan.core.settings import USER_SETTINGS
from popcan.helper.datehelper import timestamp
from popcan.helper.requesthelper import ext
from datetime import datetime
import threading
import Image

locker = threading.RLock()

class uploadAgent(object):
    
    def __init__(self):
        self.uproot = USER_SETTINGS['UPLOAD_ROOT'] + self.getRoot() + '/'
        self.urlprefix = USER_SETTINGS['UPLOAD_URL_PREFIX']
    
    def getUploadRoot(self):
        return self.uproot
    
    def getRoot(self):
        raise NotImplementedError
    
    def getMaxSize(self):
        return USER_SETTINGS['UPLOAD_MAX_SIZE']
    
    def allowed(self,exttype):
        return False
    
    def saveFile(self,userId,stream):
        raise NotImplementedError
    
    def ensureDir(self,dir_path):
        path = ''.join((self.uproot,dir_path,'/'))
        self.__ensureDir(path)
        return path
    
    def __ensureDir(self,dir_path):
        if os.path.isdir(dir_path) :
            return
        locker.acquire()
        if os.path.isdir(dir_path):
            locker.release()
            return
        try:
            head,tail = os.path.split(dir_path)
            if head :
                self.__ensureDir(head)
            if tail :
                os.mkdir(dir_path)
        finally:
            locker.release()

class DailyAgent(uploadAgent):
    
    def __init__(self):
        super(DailyAgent,self).__init__()
        self.seq = 0
    
    def getRoot(self):
        return 'user_daily'
    
    def allowed(self,exttype):
        return exttype in('gif','png','jpg','jpeg','bmp')
    
    def getPath(self,userId):
        if not userId:
            raise Exception('userId must have value')
        now = datetime.now()
        datekey = ''.join((str(now.year),str(now.month),str(now.day)))
        return '/'.join((str(userId),datekey))
    
    def getUnique(self,userId):
        self.seq += 1
        return '_'.join((str(userId),str(self.seq),str(timestamp())))
    
    def saveFile(self,userId,stream):
        path = self.getPath(userId)
        fullpath = self.ensureDir(path)
        unique = self.getUnique(userId)
        exttype = ext(stream.name)
        fname = ''.join((fullpath , unique , '.' , exttype))
        fd = open(fname,'wb')
        for chunk in stream.chunks():
            fd.write(chunk)
        fd.flush()
        fd.close()
        furl = ''.join((self.urlprefix,'/'.join((self.getRoot(),path,'.'.join((unique,exttype))))))
        
        tunique = 'thumb_' + unique
        tname = ''.join((fullpath , tunique  , '.' , exttype))
        self.saveThumb(fname,tname)
        turl = ''.join((self.urlprefix,'/'.join((self.getRoot(),path,'.'.join((tunique,exttype))))))
        return furl,turl

    def saveThumb(self,fname,tname):
        im = Image.open(fname)
        out=im.resize((64,64))
        out.save(tname)
        